import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XPathHelper {
	private Document doc;

	private static Document getXmlDocument(String filepath)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		return builder.parse(filepath);
	}

	public XPathHelper(Document doc) throws ParserConfigurationException,
			SAXException, IOException, XPathExpressionException {
		this.doc = doc;
	}

	public XPathHelper(String filepath) throws ParserConfigurationException,
			SAXException, IOException, XPathExpressionException {
		this.doc = XPathHelper.getXmlDocument(filepath);
	}

	public Object evaluate(String xpathExpr) throws XPathExpressionException {
		XPathFactory xpathFac = XPathFactory.newInstance();
		XPath xpath = xpathFac.newXPath();
		XPathExpression expr = xpath.compile(xpathExpr);
		return expr.evaluate(doc, XPathConstants.NODESET);
	}
}
